import { defineStore } from 'pinia';
import { WebSocketClient } from '../../utils/websocket';
import { ref } from 'vue';
import { set } from 'nprogress';


export default defineStore('messageStore', {
  state() {
    const park=ref(true)
    const webSocket=null
    const messageRecord=[]
    const userList=ref([])
    return {
      park,
      webSocket,
      userList,
      messageRecord,
    };
  },
  actions: {
    setPark(value){
      this.park=value
    },

    buildWebsocket(id) {
      this.webSocket=new WebSocketClient(id)
    },
    buildUserList() {
      this.userList=ref([])
    },
    buildMessageRecord() {
      this.messageRecord=[]
    },

    addUser(user) {
      this.userList.push(user);
    },

    addMessageRecord(id) {
      const ifExistence=this.messageRecord.find(user => user.id === id)

      if(!ifExistence){
        this.messageRecord.push(id)
        this.messageRecord.push([])
      }
    },

    getMessageRecord(id) {
      for(let i=0;i<this.messageRecord.length;i++){
        if(this.messageRecord[i]===id){
          return this.messageRecord[i+1]
        }
      }
    },

    toRecordMessage(id, message) {
      let recordLocal=-1
      let record=[]

      for(let i=0;i<this.messageRecord.length;i++){
        if(this.messageRecord[i]==id){
          recordLocal=i+1
          record=this.messageRecord[i+1]
          break
        }
      }

      if(recordLocal!=-1){
        record.push(message)
        this.messageRecord[recordLocal]=record
      }

    },
  },
  persist: true
});
